// https://leetcode.cn/problems/binary-tree-maximum-path-sum/?envType=study-plan-v2&envId=top-interview-150
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int maxSum = INT_MIN;
    
public:
    int maxPathSumHelper(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }

        int leftMax = max(maxPathSumHelper(root->left), 0);
        int rightMax = max(maxPathSumHelper(root->right), 0);
        int curSum = root->val + leftMax + rightMax;

        maxSum = max(curSum, maxSum);
        return root->val + max(leftMax, rightMax);
    }

    int maxPathSum(TreeNode* root) {
        maxPathSumHelper(root);
        return maxSum;
    }
};